package com.moka.db;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper{

	int newVersion = 0;
	
	int oldVersion = 0;
	
	String dbName;
	
	Context context;
	
	private static Map<String,DatabaseHelper> map = new HashMap<String,DatabaseHelper>();
	
	public static DatabaseHelper getDatabaseHelper(Context context,String dbName,int newVersion,int oldVersion){
		
		String key = dbName+"-"+newVersion+"-"+oldVersion;
		
		DatabaseHelper helper = map.get(key);
		
		if(helper==null){
			
			helper = new DatabaseHelper(context,dbName, newVersion, oldVersion);
			
			map.put(key, helper);
			
		}
		
		return helper;
		
	}
	
	
	public DatabaseHelper(Context context, String dbName,int newVersion,int oldVersion) {
		
		super(context,dbName, null, newVersion);
		
		this.context = context;
		
		this.newVersion = newVersion;
		
		this.oldVersion = oldVersion;
		
		this.dbName = dbName; 
		
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		
		if(oldVersion == 0){
			
			List<Class<?>> list = Configuration.getDatabaseEntityList(dbName);
			
			for(Class<?> clazz: list){
				
				try {
					
					DatabaseEntity entity = (DatabaseEntity)clazz.newInstance();
					
					String sql = entity.getCreateSQL();
					
					db.execSQL(sql);
					
				} catch (Exception e) {
					
					e.printStackTrace();
					
				}
				
			}
			
			DatabaseVersionManager dvm = new DatabaseVersionManager(context);
			
			dvm.setVersion("db/"+dbName, newVersion);
			
		}
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {

		if(oldVersion < newVersion){
		
			List<Class<?>> list = Configuration.getDatabaseEntityList(dbName);
			
			for(Class<?> clazz: list){
				
				try {
					
					DatabaseEntity entity = (DatabaseEntity)clazz.newInstance();
					
					String sql = entity.getUpgradeSQL(oldVersion);
					
					db.execSQL(sql);
					
				}catch(Exception e){
					
					e.printStackTrace();
					
				}
			}
			
			DatabaseVersionManager dvm = new DatabaseVersionManager(context);
			
			dvm.setVersion("db/"+dbName, newVersion);
			
		}
		
	}

}
